/**
 * Created by Spook on 2017/2/8.
 */
;(function () {
    'use strict';
    var $form_add_task = $('.add-task'),
        $body = $('body'),
        $window = $(window),
        btn = $form_add_task.find('button'),
        $delete_task,
        $task_detail_mask = $('.task-detail-mask'),
        $task_delete,
        $task_detail = $('.task-detail'),
        $task_detail_btn,
        task_list = [],
        current_index,
        $task_detial_content,
        $task_detial_content_input,
        $checkbox_complete,
        $msg = $('.msg'),
        $msg_con = $msg.find('.msg-con'),
        $msg_confirm = $msg.find('button'),
        $sound = $('.sound'),
        update_form;
    init();

    btn.on('click', on_add_task_event);
    $task_detail_mask.on('click', hide_task_detail);
    function listenMsgEvent() {
        $msg_confirm.on('click', function () {


            hideMsg();
        });
    }

    //监听 task 添加事件
    function on_add_task_event(e) {
        var new_task = {}, ipt;
        //禁用默认行为
        e.preventDefault();
        //获取新 task的值
        ipt = $form_add_task.find('input[name=con]');
        new_task.content = ipt.val();
        //如果新 task 的值为空,直接返回
        if (!new_task.content) return;
        //存入新 task
        if (add_task(new_task)) {
            render_task_list();
            ipt.val(null);
        }
    };

    function listen_task_detail() {
        $task_detail_btn.on('click', function () {
            var $this = $(this);
            var $item = $this.parent().parent();
            var index = $item.data('index');
            show_task_detail(index);
        })
    };
    //显示详情模板
    function show_task_detail(index) {
        current_index = index;
        render_task_detail(index);
        $task_detail.show();
        $task_detail_mask.show();
    };

    function update_task(index, data) {
        if (index === undefined || !task_list[index]) return;

        task_list[index] = $.extend({}, task_list[index], data);

        refrech_task_list();
    };

    function get(index) {
        return store.get('task_list')[index];
    };

    //渲染指定 task 的详细信息
    function render_task_detail(index) {
        var item = task_list[index];
        if (index === undefined || task_list[index] === undefined) return;
        var tpl = '<form>' +
            '<div class="con">' + item.content + '</div>' +
            '<div><input style="display: none" type="text" name="content" value="' + ( item.content || "") + '"></div>' +
            '<div>' +
            '<div class="desc">' +
            '<textarea name="desc">' + (item.desc || "" ) + '</textarea>' +
            '</div>' +
            '</div>' +
            '<div class="remind">' +
            '<p class="lb-time">提醒时间:</p>' +
            '<input class="dataTime" name="remind_date" value="' + (item.remind_data || '') + '" type="text">' +
            '<div class="sub_btn"><button type="submit">更新</button></div>' +
            '</div>' +
            '</form>';
        $task_detail.html(null);
        $task_detail.html(tpl);
        $('.dataTime').datetimepicker()
        update_form = $task_detail.find('form');
        $task_detial_content = update_form.find('.con');
        $task_detial_content_input = update_form.find('input[name="content"]');
        //绑定内容双击事件 切换 input 标签
        $task_detial_content.on('dblclick', function () {
            $task_detial_content_input.show();
            $task_detial_content.hide();
        });
        $task_detial_content.on()
        update_form.on('submit', function (e) {
            e.preventDefault();
            var data = {};
            data.content = $(this).find('[name = content]').val();
            data.desc = $(this).find('[name = desc]').val();
            data.remind_data = $(this).find('[name = remind_date]').val();
            update_task(index, data);
            hide_task_detail();
        })

    };
    //隐藏详情遮罩
    function hide_task_detail() {
        $task_detail.hide();
        $task_detail_mask.hide();
    };

    //监听删除事件
    function listen_task_delete() {
        var index;
        $('.task-item').on('dblclick', function () {
            index = $(this).data('index');
            show_task_detail(index);
        });
        //删除选择项
        $task_delete.on('click', function () {
            var $this = $(this);
            //获取删除按钮所有的 task 元素
            var $item = $this.parent().parent();
            index = $item.data('index');

            pop('确定删除?').then(function (r) {
                r ? delete_task(index) : null;
            })
        })
    };
    //自定义弹框
    function pop(arg) {
        if (!arg) {
            console.error('pop title is required');
        }
        var conf = {},
            $box,
            $mask,
            $title,
            $con,
            $confirm,
            $concel,
            dfd,
            confirmed,
            timer
            ;
        if (typeof arg == 'string') {
            conf.title = arg;
        } else {
            conf = $.extend(conf, arg);
        }

        dfd = $.Deferred();
        $box = $('<div>' +
            '<div class="pop-tit ">' + conf.title + '</div>' +
            '<div class="pop-con">' +
            '<div>' +
            '<button type="button" class="primary confirm">确定</button>　' +
            '<button class="cancel" type="button">取消</button>' +
            '</div>' +
            '</div>' +
            '</div>')
            .css({
                color: '#444',
                position: 'fixed',
                width: 300,
                height: 'auto',
                borderRadius: 3,
                boxShadow: '0 1px 2px rgba(0,0,0,.3 )',
                background: '#FFF',
                padding: '20px 0'
            });
        $title = $box.find('.pop-tit').css({
            padding: '5px 10px',
            fontWeight: '900',
            fontSize: '20px',
            textAlign: 'center'
        });
        $con = $box.find('.pop-con').css({
            padding: '5px 10px',
            fontWeight: '9 00',
            textAlign: 'center'
        });
        $confirm = $con.find('button.confirm');
        $concel = $con.find('button.cancel');


        $mask = $('<div></div>').css({
            position: 'fixed',

            background: 'rgba(0, 0, 0, 0.5)',
            top: 0,
            right: 0,
            bottom: 0,
            left: 0
        });
        timer = setInterval(function () {
            if (confirmed !== undefined) {
                dfd.resolve(confirmed);
                clearInterval(timer);
                disMissPop();
            }
        }, 50)
        // 确定事件
        $confirm.on('click', eventConfirm);
        //取消事件
        $concel.on('click', eventCancel);
        //点击 mask 隐藏遮罩
        $mask.on('click', function () {
            eventCancel();
        });
        function eventCancel() {
            confirmed = false;
        };
        function eventConfirm() {
            confirmed = true;
        }


        //删除弹框
        function disMissPop() {
            $mask.remove();
            $box.remove();
        };
        function adjustBoxPosition() {
            var winWidth = $window.width(),
                winHeight = $window.height(),
                boxWidth = $box.width(),
                boxHeight = $box.height(),
                moveX,
                moveY;
            moveX = (winWidth - boxWidth) / 2;
            moveY = ((winHeight - boxHeight) / 2) - 30;
            $box.css({
                left: moveX,
                top: moveY
            });
        };
        $window.on('resize', function () {
            adjustBoxPosition();
        });

        $body.append($mask, $box);
        $window.resize();
        return dfd.promise();
    };
    //监听选择框事件
    function listen_checkbox_complete() {
        $checkbox_complete.on('click', function () {
            var $this = $(this);

            var index = $this.parent().parent().data('index');
            var item = get(index);
            if (item.complete) {
                update_task(index, {complete: false});
            } else {
                update_task(index, {complete: true});
            }
        });
    };
    function add_task(new_task) {
        //将新 task 推入 task_list
        task_list.push(new_task);
        //更新localStorage
        store.set('task_list', task_list);
        return true;
    };

    function init() {
        task_list = store.get('task_list') || [];
        if (task_list.length) {
            render_task_list();
        }
        task_remind_check();
        listenMsgEvent();
    };
    function task_remind_check() {
        // showMsg();
        var current_time_stamp;
        var itl = setInterval(function () {
            for (var i = 0; i < task_list.length; i++) {
                var item = get(i), taskTimeStamp;
                if (!item || !item.remind_data || item.informed) {
                    continue;
                }
                //当前的时间
                current_time_stamp = (new Date()).getTime();
                //定义的提醒时间
                taskTimeStamp = (new Date(item.remind_data)).getTime();
                console.log(current_time_stamp, taskTimeStamp);
                if (current_time_stamp - taskTimeStamp >= 1) {
                    update_task(i, {informed: true});
                    showMsg(item.content +':'+ item.desc);
                }
            }
        }, 500)
    };
    //提醒
    function showMsg(con) {
        $msg_con.html(con);
        $msg.show();
        $sound.get(0).play();

    };
    function hideMsg() {
        $msg.hide();
    };

    //渲染全部 task TPL
    function render_task_list() {
        var $task_list = $('.tasks-list');
        $task_list.html('');
        var complete_item = [];
        for (var i = 0; i < task_list.length; i++) {
            var item = task_list[i];
            if (item && item.complete) {
                complete_item[i] = item;
            } else {
                var $task = render_task_item(task_list[i], i);
                $task_list.prepend($task);
            }
        }
        ;
        for (var j = 0; j < complete_item.length; j++) {
            $task = render_task_item(complete_item[j], j);
            if (!$task) continue;
            $task.addClass('completed');
            $task_list.append($task);
        }
        $task_delete = $('.action.delete');
        $task_detail_btn = $('.action.detail');
        $checkbox_complete = $('.complete[type=checkbox]');
        //调用删除
        listen_task_delete();
        //调用详情
        listen_task_detail();
        //调用
        listen_checkbox_complete();
    };

    //刷新 localStorage数据 并更新 渲染TPL
    function refrech_task_list() {
        store.set('task_list', task_list);
        render_task_list();
    };
    //删除单个 task
    function delete_task(index) {
        //    如果没有找到 Index 或者 index不存在 刚直接返回
        if (index === undefined || !task_list[index]) return;
        delete task_list[index];
        //删除对应 index 以后 更新 Storate
        refrech_task_list();
    };
    //渲染单个 task TPL
    function render_task_item(data, index) {
        if (!data || index === undefined) return;

        var task_list_tpl =
            '<div class="task-item" data-index="' + index + '">' +
            '<span><input class="complete" ' + (data.complete ? 'checked' : '') + ' type="checkbox"></span>' +
            '<span class="task-con">' + data.content + '</span>' +
            '<span class="fr">' +
            '<span class="action delete"> 删除</span>' +
            '<span class="action detail"> 详情</span>' +
            '</span>' +
            '</div>';
        return $(task_list_tpl);
    };
})();
